package com.lnking.lnkingplace.service.impl;

import com.lnking.lnkingplace.Util.ImageUtils;
import com.lnking.lnkingplace.Util.UserUtil;
import com.lnking.lnkingplace.mapper.FileListMapper;
import com.lnking.lnkingplace.model.entity.FileList;
import com.lnking.lnkingplace.service.IUploadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author 联坤
 */
@Service
public class UploadServiceImpl implements IUploadService {

     public static final Long MAX=10485760L;

    @Value("${upload.location}")
    String baseUploadPath;

    @Value("${upload.prefix}")
    String prefix;

    /**
     * 返回前端的文件路径的前缀
     */
    @Value("${upload.file-path-prefix}")
    String filePathPrefix;

    @Value("${image.compress.size}")
    Integer imageCompressSize;


    @Resource
    FileListMapper fileMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FileList uploadFile(MultipartFile file, String creatorName) throws Exception {
        Assert.isTrue(file.getSize()<=MAX,"文件超过大小极限");
        // 将文件储存起来
        String[] fileInfo = getFileSaveName(file);
        String fileSaveName = fileInfo[0];
        String path = saveFile(file, fileInfo[1]);

        // 将记录插入附件表
        FileList fileEntity = new FileList();
        fileEntity.setFileName(file.getOriginalFilename());
        fileEntity.setSaveName(fileSaveName);
        fileEntity.setUploadTime(LocalDateTime.now());
        fileEntity.setPath(path);
        fileEntity.setSize(file.getSize());
        fileEntity.setCreatorName(creatorName);
        fileMapper.insert(fileEntity);

        // 这里要把服务器的IP信息加入返回数据内
        fileEntity.setPath(filePathPrefix + fileEntity.getPath());
        return fileEntity;
    }

    private String[] getFileSaveName(MultipartFile file) {
        String saveName = "";
        String suffixName = "";
        String fileName = file.getOriginalFilename();
        if(fileName.lastIndexOf(".") > 0) {
            String[] arr = fileName.split("\\.");
            String firstName = arr[0];
            suffixName = arr[arr.length - 1];
            saveName = firstName + "-" + System.currentTimeMillis() + "." + suffixName;
        }
        else {
            saveName = fileName;
        }
        return new String[] { saveName, suffixName} ;
    }

    private String saveFile(MultipartFile file, String type) throws IOException {
        String fileName = file.getOriginalFilename();
        String suffixName = "." + type;
        fileName = UserUtil.getUUID() + suffixName;
        String absPath = baseUploadPath + java.io.File.separator + fileName;
        java.io.File dest = new java.io.File(absPath);
        // 创建路径
        if(!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }

        file.transferTo(dest);

        // 如果是图片，则对图片进行压缩
        String[] imageSuffix = {"jpg", "jpeg", "png"};
        if (Arrays.asList(imageSuffix).contains(type.toLowerCase())) {
            ImageUtils.compressPicCycle(absPath, imageCompressSize, 0.7);
        }

        String url = prefix + java.io.File.separator + fileName;
        return url;
    }
}
